package cn.cosmosx.base.security.dynamic;


import cn.cosmosx.base.constant.AuthSwitch;
import cn.cosmosx.base.security.service.CacheProviderService;
import cn.cosmosx.entity.vo.RolePermsVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 自定义动态权限获取，用于返回定义好的权限资源
 * {@link FilterInvocationSecurityMetadataSource} 的实现.<br>
 * 为 {@link org.springframework.security.access.AccessDecisionManager} 提供 configAttributes
 */
@Slf4j
@Component
public class DynamicFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    // 可访问标识
    protected static final String ROLE_ANONYMOUS = "ROLE_ANONYMOUS";

    @Autowired
    private CacheProviderService cacheProviderService;
    // 角色权限
    List<RolePermsVO> rolePerms;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        // 因为 supports 方法只放行了 FilterInvocation 和其父类以及接口, 所以
        // 总是 dynamic filter invocation security metadata source, getAttributes: org.springframework.security.web.FilterInvocation
        FilterInvocation filterInvocation = (FilterInvocation) object;
        if (filterInvocation.getRequestUrl().equals("/error")) {
            return SecurityConfig.createList(ROLE_ANONYMOUS);
        }
        // 无权限白名单-不需要登录
        if (AuthSwitch.matchWhiteList(filterInvocation.getRequest())) {
            return SecurityConfig.createList(ROLE_ANONYMOUS);
        }
        // 登录可访问名单-登录后可访问
        if (AuthSwitch.matchAuthedList(filterInvocation.getRequest())) {
            return SecurityConfig.createList(ROLE_ANONYMOUS);
        }
        final String requestUrl = filterInvocation.getRequestUrl();
        log.info("{}#getAttributes:{}", this.getClass().getName(), requestUrl);

        // 获取角色和权限的对应关系，找到匹配当前url的角色，并放到SecurityConfig中
        rolePerms = cacheProviderService.getAndCacheRolePerms();
        if (rolePerms.isEmpty()) {
            throw new InsufficientAuthenticationException("缺少权限配置");
        }
        Set<String> roles = rolePerms.stream()
                .filter(x -> StringUtils.isNoneEmpty(x.getPermUrl()) && StringUtils.isNoneEmpty(x.getRoleCode()))
                .filter(item -> new AntPathMatcher().match(item.getPermUrl(), requestUrl))
                .map(RolePermsVO::getRoleCode).collect(Collectors.toSet());
        // 如果返回 null 或者 空集合, 不会调用 AccessDecisionManager 的 decide 方法,
        if (!roles.isEmpty()) {
            return SecurityConfig.createList(roles.toArray(new String[0]));
        }
        throw new InsufficientAuthenticationException("权限不足");
    }

    /**
     * 返回所有定义好的权限资源，Spring Security启动时会校验相关配置是否正确，如果不需要校验，直接返回null即可
     */
    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        log.info("{}#getAllConfigAttributes", this.getClass().getName());
        rolePerms = cacheProviderService.getAndCacheRolePerms();
        return SecurityConfig.createList(rolePerms.stream()
                .filter(x -> StringUtils.isNoneEmpty(x.getPermUrl()))
                .map(RolePermsVO::getRoleCode).distinct().toArray(String[]::new));
    }

    @Override
    public boolean supports(Class<?> clazz) {
        log.info("{}#supports:{}", this.getClass().getName(), clazz.getCanonicalName());
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}

